package cn.smbms.controller;

import cn.smbms.pojo.Role;
import cn.smbms.pojo.User;
import cn.smbms.service.role.RoleService;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;
import cn.smbms.tools.PageSupport;
import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import lombok.extern.log4j.Log4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @Auther: liyuxuan
 * @Date:2021/11/8 - 11 - 08 - 11:45
 */
@Log4j
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String doLogin(HttpServletRequest request, HttpSession session, @RequestParam String userCode, @RequestParam String userPassword) {
        User user = this.userService.login(userCode, userPassword);
        if (user != null) {
            if (user.getPassword().equals(userPassword)) {
                session.setAttribute("userSession", user);
                return "redirect:/user/toMain";
            } else {
                throw new RuntimeException("密码错误");
            }
        } else {
            throw new RuntimeException("账号不存在");
        }
    }

    @RequestMapping("/toLogin")
    public String login() {
        log.debug("跳转到登录页面");
        return "/login";
    }

    @RequestMapping("/toMain")
    public String main(HttpSession session) {
        if (session.getAttribute("userSession") == null) {
            return "redirect:/user/toLogin";
        } else {
            log.debug("跳转到首页");
            return "jsp/frame";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session, HttpServletRequest request) {
        request.getSession().invalidate();
        return "redirect:/user/toLogin";
    }

    @GetMapping("/userList")
    public String userList(Model model, String queryUserName, Integer queryUserRole, @RequestParam(defaultValue = "1") Integer pageIndex) {
        List userList = null;

        try {
            if (queryUserName == null) {
                queryUserName = "";
            }

            if (queryUserRole == null) {
                queryUserRole = 0;
            }

            int pageSize = Constants.pageSize;
            int totalCount = this.userService.getUserCount(queryUserName, queryUserRole);
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalCount(totalCount);
            int totalPageCount = pages.getTotalPageCount();
            if (pageIndex > totalPageCount) {
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            } else {
                userList = this.userService.getUserList(queryUserName, queryUserRole, pageIndex, pageSize);
                model.addAttribute("userList", userList);
                List<Role> roleList = null;
                roleList = this.roleService.getAllRoleList();
                model.addAttribute("roleList", roleList);
                model.addAttribute("queryUserName", queryUserName);
                model.addAttribute("queryUserRole", queryUserRole);
                model.addAttribute("totalPageCount", totalPageCount);
                model.addAttribute("totalCount", totalCount);
                model.addAttribute("currentPageNo", pageIndex);
                return "/jsp/userlist";
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.debug("用户表接口访问失败");
            return "/jsp/error";
        }
    }
/*    @ExceptionHandler(value = {Exception.class})
    public String exceptionHandler(Exception e,HttpServletRequest request){
        request.setAttribute("e",e);
        return "/login";
    }*/

    @GetMapping("/toAdd")
    public String toAdd(){
        return "/jsp/useradd";
    }
    @PostMapping("/add")
    public String add (User user, HttpSession session, HttpServletRequest request, @RequestParam(value = "idPic",required = false) MultipartFile[] idPic){
        String idPicPath = null;
        List<String> list = new ArrayList<>();
        if (idPic!=null){
            String path = request.getSession().getServletContext().getRealPath("statics"+File.separator+"uploadFiles");
            for (int i = 0; i < idPic.length; i++) {
                log.info("上传文件路径"+path);
                String originalFile = idPic[i].getOriginalFilename();
                log.info("原文件名为："+originalFile);
                String prefix = FilenameUtils.getExtension(originalFile);
                log.debug("原文件后缀为："+prefix);
                log.debug("文件大小："+idPic[i].getSize());
                if (prefix.equalsIgnoreCase("jpg")||prefix.equalsIgnoreCase("png")||prefix.equalsIgnoreCase("jpeg")||prefix.equalsIgnoreCase("pneg")) {
                    String fileName = System.currentTimeMillis()+ RandomUtils.nextInt(1000000)+"_Personal."+prefix;
                    log.debug("生成新的文件名称为："+fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()){
                        targetFile.mkdirs();
                    }
                    try {
                        idPic[i].transferTo(new File(targetFile,fileName));

                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("uploadFileError","* 上传失败");
                        return "/jsp/useradd";
                    }
                    idPicPath = File.separator+"statics"+File.separator+"uploadFiles"+File.separator+fileName;
                    list.add(idPicPath);
                } else {
                    request.setAttribute("uploadFileError","* 上传图片格式不正确");
                    return "/jsp/useradd";
                }
            }
        }
        user.setCreatedBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setCreationDate(new Date());
        user.setIdPicPath(list.get(0));
        user.setWorkPicPath(list.get(1));
        if (userService.add(user)) {
            return "redirect:/user/userList";
        }
        return "/jsp/useradd";
    }
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id,Model model){
        log.debug("根据ID查询用户详情"+id);
        User user = userService.getUserById(id);
        model.addAttribute(user);
        return "/jsp/userview";
    }
    @GetMapping("/toModify/{id}")
    public String toModify(@PathVariable String id,Model model){
        User user = userService.getUserById(id);
        model.addAttribute(user);
        return "/jsp/usermodify";
    }
    @PostMapping("/modify")
    public String modify(User user,HttpSession session){
        log.debug("修改用户信息");
        user.setModifyBy(((User)session.getAttribute(Constants.USER_SESSION)).getId());
        user.setModifyDate(new Date());
        if (userService.modify(user)) {
            return "redirect:/user/userList";
        }
        return "/jsp/usermodify";
    }
    @ResponseBody
    @GetMapping(value = {"/userExist/{userCode}","/userExist"})
    public Object userExist(@PathVariable(required = false) String userCode){
        log.debug("验证用户名userCode"+userCode+"的用户是否存在");
        HashMap<String ,Object> resultMap = new HashMap<>();
        if (StringUtils.isNullOrEmpty(userCode)) {
            resultMap.put("exist",1);
        } else {
            User user = userService.selectUserCodeExist(userCode);
            if (null != user) {
                resultMap.put("exist",1);
            } else {
                resultMap.put("exist",0);
            }
        }
        return JSON.toJSONString(resultMap);
    }
    @ResponseBody
    @GetMapping(value = "/{id}/view",produces = {"application/json;charset=UTF-8"})
    public Object view(@PathVariable String id ){
        log.debug("根据id查询用户详情，id："+id);
        User user = null;
        //String userJSON = "";
        if (null == id || "".equals(id)) {
            return "nodata";
        } else {
            try {
                user = userService.getUserById(id);
                //userJSON = JSON.toJSONString(user);
                log.debug("用户信息转换为JSON:"+user.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return "failed";
            }
            return user;
        }
    }
    @ResponseBody
    @GetMapping(value = {"/pwdmodify/{password}","/pwdmodify"})
    public Object pwdmodify(@PathVariable(required = false) String password,HttpSession session){
        String oldpwd = (((User)session.getAttribute(Constants.USER_SESSION)).getPassword());
        HashMap<String,Object> map = new HashMap<>();
        if(oldpwd!=null&&oldpwd!=""){
            if(password!=null&&password!="") {
                if (oldpwd.equals(password)) {
                    map.put("result", "true");
                } else {
                    map.put("result", "false");
                }
            }else{
                map.put("result","error");
            }
        }else{
            map.put("result","sessionerror");
        }
        return map;
    }

    @RequestMapping("/toPwdModify")
    public String toPwdModify(){
        return "/jsp/pwdmodify";
    }

    @PostMapping("/passwordModify")
    public String passwordModify(@RequestParam String newpassword,HttpSession session,Model model){
        Integer uid = (((User)session.getAttribute(Constants.USER_SESSION)).getId());
        String password = ((User) session.getAttribute(Constants.USER_SESSION)).getPassword();
        if (!password.equals(newpassword)) {
            if (userService.updatePwd(uid, newpassword)) {
                session.invalidate();
                model.addAttribute("message", "密码修改成功!");
                return "/login";
            } else {
                model.addAttribute("message", "修改失败!");
            }
        } else {
            model.addAttribute("message","旧密码与新密码相同,修改失败!");
        }
        return "/jsp/pwdmodify";
    }

    @ResponseBody
    @GetMapping("/getRoleList")
    public Object getRoleList(){
        List<Role> role = roleService.getAllRoleList();
        return role;
    }

    @ResponseBody
    @GetMapping("/delUser/{id}")
    public Object delUser(@PathVariable String id,Model model,HttpServletRequest request){
        User user = userService.getUserById(id);
        String path = request.getSession().getServletContext().getRealPath("");
        if (user!=null) {
            if(user.getIdPicPath()!=null){
                String[] fileName = {path+user.getIdPicPath(),path+user.getWorkPicPath()};
                for (int i = 0; i < fileName.length; i++) {
                    File file = new File(fileName[i]);
                    file.delete();
                }
            }
            if(userService.deleteUserById(Integer.parseInt(id))){
                model.addAttribute("delResult","true");
            } else {
                model.addAttribute("delResult","false");
            }
        } else {
            model.addAttribute("delResult","notexist");
        }
        return model;
    }
}